package com.qf.staff.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.common.base.exception.ServiceException;
import com.qf.common.base.result.ResultCode;
import com.qf.common.db.utils.PageCommonBeanUtils;
import com.qf.staff.common.qo.PayrollQo;
import com.qf.staff.common.vo.PayrollVo;
import com.qf.staff.mapper.PayrollMapper;
import com.qf.staff.pojo.Payroll;
import com.qf.staff.service.PayrollService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class PayrollServiceImpl implements PayrollService {
    @Resource
    PayrollMapper payrollMapper;

    @Override
    public IPage<PayrollVo> list(int page, int size) {
        try {
            return PageCommonBeanUtils.copyPage(payrollMapper.selectPage(new Page<>(page, size), null),
                    new Page<>(), PayrollVo::new);
        } catch (Exception e) {
            throw new ServiceException(ResultCode.QUERY_ERROR);
        }
    }

    @Override
    public int delete(PayrollQo payrollQo) {
        try {
            Payroll payroll = new Payroll();
            BeanUtils.copyProperties(payrollQo, payroll);
            return payrollMapper.updateByStatus(payroll);
        } catch (BeansException e) {
            throw new ServiceException(ResultCode.DELETE_ERROR);
        }
    }

    @Override
    public int modify(PayrollQo payrollQo) {
        try {
            Payroll payroll = new Payroll();
            BeanUtils.copyProperties(payrollQo, payroll);
            return payrollMapper.updateById(payroll);
        } catch (BeansException e) {
            throw new ServiceException(ResultCode.UPDATE_ERROR);
        }
    }

    @Override
    public int add(PayrollQo payrollQo) {
        try {
            Payroll payroll = new Payroll();
            BeanUtils.copyProperties(payrollQo, payroll);
            return payrollMapper.insert(payroll);
        } catch (BeansException e) {
            throw new ServiceException(ResultCode.INSERT_ERROR);
        }
    }

    @Transactional
    @Override
    public int deleteAll(List<Integer> ids, int status) {
        try {
            int num = payrollMapper.updateByAllStatus(ids, status);
            if (num < ids.size()) {
                throw new ServiceException(ResultCode.DELETE_ERROR);
            }
            return num;
        } catch (Exception e) {
            throw new ServiceException(ResultCode.DELETE_ERROR);
        }
    }
}
